<?php

namespace app\index\middleware;

use think\facade\Request;
use Firebase\JWT\JWT;
use app\index\model\UserModel;
use Firebase\JWT\Key;

class Openness
{
    public function handle($request, \Closure $next)
    {
        $token = Request::header('T');
        if (empty($token)) {
            return result()->fail("token不能为空", 401);
        }
        $decoded = JWT::decode($token, new Key(config('app.jwt.secret'), config('app.jwt.algo')));
        if ($decoded->ext < time()) {
            return $next($request);
        }
        $text = $decoded->data->id;
        $arr = explode(":", $text);
        if($arr[0] != 'USER') {
            return $next($request);
        }
        $userId = $arr[1];
        $sql = new UserModel();
        $user = $sql->findOrEmpty($userId);
        if($user->isEmpty()) {
            return $next($request);
        }
        $password = $decoded->data->password;
        if($user->password != $password) {
            return $next($request);
        }
        $request->user = $user;
        return $next($request);
    }
}